﻿#include "Loot.h"
#include "Map.h"
#include "SimpleAudioEngine.h"
#pragma execution_character_set("utf-8")
Loot::Loot()
{
	MoveTimer = 0.5f;
	FallingTimer = 0.5f;
	m_RemoveTimer = 30.0f;
	scheduleUpdate();
	IsMoveDone = false;
	Looter = nullptr;
	m_Onwer = nullptr;
}

Loot::~Loot()
{
	RemoveFromMap();
}

void Loot::IsLootingByPlayer(Player* pPlayer)
{
	if (!IsMoveDone)
		return;
	if (!pPlayer->GetBag()->HasEmptySlot())
	{
		pPlayer->SendNotify("没有足够的背包空间!");
		return;
	}
	CocosDenshion::SimpleAudioEngine::getInstance()->sharedEngine()->playEffect("sound/action/PickUpItem.mp3");
	Looter = pPlayer;
	pPlayer->AddItem(m_ItemEntry, m_Count);
	RemoveFromMap();
	CCFadeOut* Fadeout = CCFadeOut::create(1.0f);
	CCSequence* spawn = CCSequence::create(Fadeout, CallFunc::create(CC_CALLBACK_0(Loot::DesTorySprite, this)), NULL);
	runAction(spawn);
}

void Loot::DesTorySprite()
{
	removeFromParentAndCleanup(true);
}

void Loot::RemoveFromMap()
{
	Map_Layer::GetInstance()->RemoveLoot(this);
}

void Loot::AddToMap()
{
	Map_Layer::GetInstance()->AddLoot(this);
}

void Loot::update(float diff)
{
	if (MoveTimer >= 0)
	{
		if (getPositionX() != m_MovePostionX)
		{
			m_SingleMoveX = (m_MovePostionX - m_BasePostionX) * diff * 2;
			setPositionX(getPositionX() + m_SingleMoveX);
		}
		float thisposy = getPositionY();
		if (thisposy != m_MovePostionY)
		{
			m_SingleMoveY = (m_MovePostionY - m_BasePostionY) * diff * 2;
			setPositionY(thisposy + m_SingleMoveY);
		}
		MoveTimer -= diff;
		m_FallingBasePosY = getPositionY();
		return;
	}
	if (FallingTimer >= 0)
	{
		m_SingleMoveY = (m_FallingBasePosY - m_BasePostionY) * diff * 2;
		if (getPositionY() >= m_BasePostionY)
		{
			setPositionY(getPositionY() - m_SingleMoveY);
		}
		FallingTimer -= diff;
		return;
	}
	else
	{
		IsMoveDone = true;
	}

	if (Looter)
	{
		float tempmovex = (Looter->getPositionX() - getPositionX()) * diff * 3;
		float tempmovey = (Looter->getPositionY() - getPositionY()) * diff * 3;
		setPositionX(getPositionX() + tempmovex);
		setPositionY(getPositionY() + tempmovey);
	}
	else
	{
		if (m_RemoveTimer <= diff)
		{
			DesTorySprite();
		}
		else m_RemoveTimer -= diff;
	}
}